/* 缓存 */
class Buffer{
	constructor(gl, data=null, opt={}){
		const {
			bindPoint=gl.ARRAY_BUFFER, //其它值：ELEMENT_ARRAY_BUFFER
			usage=gl.STATIC_DRAW //其它值：DYNAMIC_DRAW, STREAM_DRAW
		} = opt;
		this.gl = gl;
		this.data = data;
		
		//创建VBO
		const buffer = gl.createBuffer(); //先创建一个缓存对象
		this.object = buffer;
		gl.bindBuffer(bindPoint, buffer); //绑定至指定绑定点
		gl.bufferData(bindPoint, data, usage); //写入坐标数据
	}
	
	bind(bindPoint=this.gl.ARRAY_BUFFER){
		this.gl.bindBuffer(bindPoint, this.object); //绑定至指定绑定点
		return this;
	}
	
	unbind(bindPoint=this.gl.ARRAY_BUFFER){
		this.gl.bindBuffer(bindPoint, null);
		return this;
	}
	
	//安全绑定
	bindSafe(bindPoint=this.gl.ARRAY_BUFFER, func){
		//保存状态
		let bindingBuffer;
		switch (bindPoint){
			case this.gl.ARRAY_BUFFER:
				bindingBuffer = this.gl.getParameter(this.gl.ARRAY_BUFFER_BINDING);
				break;
			default:
				throw "[Buffer] Unknown BindPoint:" + bindPoint;
		}
		//改变状态
		this.gl.bindBuffer(bindPoint, this.object);
		func();
		//恢复状态
		this.gl.bindBuffer(bindPoint, bindingBuffer);
		return this;
	}
	
	
	setData(data=null, opt={}){
		const {
			bindPoint=this.gl.ARRAY_BUFFER, //其它值：ELEMENT_ARRAY_BUFFER
			usage=this.gl.STATIC_DRAW //其它值：DYNAMIC_DRAW, STREAM_DRAW
		} = opt;
		this.data = data;
		this.gl.bindBuffer(bindPoint, this.object); //绑定至指定绑定点
		this.gl.bufferData(bindPoint, data, usage); //写入坐标数据
	}
	
	setSubData(data=null, opt={}){
		const {
			offset=0,
			bindPoint=this.gl.ARRAY_BUFFER //其它值：ELEMENT_ARRAY_BUFFER
		} = opt;
		this.data = data;
		this.gl.bindBuffer(bindPoint, this.object); //绑定至指定绑定点
		this.gl.bufferSubData(bindPoint, offset, data); //写入坐标数据
	}
}